package datatypes;

import exceptions.MCConnectionException;
import exceptions.MCUnknownElementException;
import network.ConnectionReader;

public class MCItemSlot {
	
	private MCItem item;
	
	/**
	 * Defines the number of items represented as this item.
	 * Thus, the current stackcount.
	 */
	private int itemcount;

	private short itemmetadata;
	
	
	public MCItemSlot(MCItem item, int itemcount, short itemmetadata) {
		this.item = item;
		this.itemcount = itemcount;
		this.itemmetadata = itemmetadata;
	}
	
	
	/**
	 * Returns the item type for this itemslot.
	 * @return
	 */
	public MCItem getItem() {
		return item;
	}
	
	
	public int getStackCount() {
		return itemcount;
	}
	
	public short getMetaData() {
		return itemmetadata;
	}
	
	
	/**
	 * 
	 * @param r
	 * @return null if the "empty" item was sent, otherwsie a new MCSlotItem.
	 * @throws MCConnectionException
	 */
	public static MCItemSlot readFromSocket(ConnectionReader r) throws MCConnectionException {
		short itemid = r.readShort();

		if(itemid == -1) {
			return null;
		}
		
		byte itemcount = (byte) r.read();
		short metadata = r.readShort();	
		
		MCItem item;
		try {
			item = MCItem.getObject(itemid);
			if(item.canTakeDamage()) {
				//a short with the length of gzipped additional data is sent
				short rawextrainfolength = r.readShort();
				if(rawextrainfolength != -1) {
					r.readBytes(rawextrainfolength);
					//TODO This info has to be uncompressed (GZipped)... and then parsed somehow
					System.out.println("Got additional item information: this is thrown away!");
				}
			}
		} catch(MCUnknownElementException e) {
			item = MCItem.UNKNOWN;
		}

		
		return new MCItemSlot(item, itemcount, metadata);
	}
}
